import { container, singleton } from "tsyringe";
import { Task } from "../autox/task";
import { formatMinute, formatTime, updateFloat } from "../utils";
/**
 * 计划任务
 */
export interface IScheduleTask {
    /**
     * 执行多长时间
     */
    time: number;
    /**
     * 
     */
    sleep?: number;
    /**
     * 任务标题
     */
    title: string;
    /**
     * 是否在执行中
     */
    isRuning: boolean;
    /**
     * 执行
     */
    start(): void;
    /**
     * 停止
     */
    stop(): void;
    /**
     * 检查
     */
    check(): boolean;
}
// 定义节点类
export class TaskNode {
    data: IScheduleTask;
    next: TaskNode;
    constructor(data: IScheduleTask) {
        this.data = data; // 存储数据
        this.next = null; // 指向下一个节点的引用
    }
}

// 定义循环链表类
@singleton()
export class CircularTaskManager<T> {
    head: TaskNode;
    task: Task;
    constructor() {
        this.head = null; // 头部节点的引用
        this.task = container.resolve(Task)
    }
    /**
     * 在尾部添加新节点
     * @param IScheduleTask value 任务节点
     */
    add(value: IScheduleTask) {
        const newNode = new TaskNode(value);
        if (!this.head) {
            this.head = newNode;
            this.head.next = this.head; // 将头结点与自身连接起来形成循环
        } else {
            let current = this.head;
            while (current.next !== this.head) {
                current = current.next;
            }
            current.next = newNode;
            newNode.next = this.head;
        }
    }
    /**
     * 开始执行
     */
    run() {
        if (!this.head) {
            throw new Error(`暂无任务`)
        }
        const mainTask = this.task.start(() => {
            let current = this.head;
            do {
                // 从服务器获取红包
                // 进入直播间
                updateFloat({ toast: `正在执行${current.data.title}任务` })
                const t = this.task.start(() => {
                    device.wakeUpIfNeeded()
                    if (current.data.check()) {
                        current.data.start();
                    }
                });
                t.waitFor()
                t.join(current.data.time)
                current.data.stop();
                current = current.next;
                let sleepTime1 = random(20, 30)
                while (sleepTime1 > 0) {
                    sleepTime1 -= 1;
                    updateFloat({ toast: `${formatMinute(sleepTime1)}后返回桌面` })
                    sleep(1000)
                    device.wakeUpIfNeeded()
                }
                home()
                let sleepTime2 = random(30, 60)
                while (sleepTime2 > 0) {
                    sleepTime2 -= 1;
                    updateFloat({ toast: `${formatMinute(sleepTime2)}后执行下一个任务` })
                    sleep(1000)
                    device.wakeUpIfNeeded()
                }
            } while (true);
        });
        mainTask.waitFor();
        updateFloat({ toast: `应用启动成功` })
    }
}
